const puppeteer = require('puppeteer')
const ipUrl = 'http://www.goubanjia.com/'

module.exports = (fastify) => async (request, reply) => {
  fastify.log.info('page loading...')
  // start headless browser
  const browser = await puppeteer.launch({headless: true})
  // get link list
  const page = await browser.newPage()
  await page.goto(ipUrl)
  await page.waitFor('.ip')
  const list = await page.evaluate(async () => {
    const listIp = document.querySelectorAll('.ip')
    const res = []
    // why use list instead of res,there is not result,list is a nodelist
    for (let i = 0; i < listIp.length; i++) {
      res[i] = listIp[i].innerText
    }
    // should use page.on('console') if you use console.log
    return res
  })
  await browser.close()
  return list
}
